//
//  M_FavListVC.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/27.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD
import MJRefresh

class M_FavListVC: BaseViewControllerWithHeader,UITableViewDataSource,UITableViewDelegate {
    var tableView = UITableView(frame: CGRect.zero, style: .plain)
    var dataListAry = [[String : Any?]]()
    var pageIndex = 1
    var pageSize = 2000
    var totalSize = 2000
    var editRow : IndexPath?
    
    lazy var defultView : UIView = {
        let v = UIView()
        v.backgroundColor = .clear
        tableView.drawView(view: v) { (make) in
            make.left.top.equalToSuperview()
            make.height.width.equalToSuperview()
        }
        let img = v.drawImage(named: "sousuokong") { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-80)
            make.height.width.equalTo(200)
        }
        img.contentMode = .scaleAspectFit
        
        v.drawLabel(text: "暂无收藏商品", fontSize: 19, textColor: .x333333) { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(img.snp.bottom).offset(10)
        }.textAlignment = .center
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        refreshAll()
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    func getDataList(zoneCode :String,pageIndex: Int, pageSize:Int) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "zoneCode":zoneCode,
                                    "pageIndex":pageIndex,
                                    "pageSize":pageSize]
        API.request(url: .M_GetCollectedList, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                if let dl = result.data?.getDictionary("data") {
                    self.dataListAry.removeAll()
                    for item in dl.getDictList("items") ?? [] {
                        self.dataListAry.append(item)
                    }
                    self.pageIndex = dl.getInt("pageIndex") ?? 0
                    self.pageSize = dl.getInt("pageSize") ?? 0
                    self.totalSize = dl.getInt("totalSize") ?? 0
                    self.tableView.reloadData()
                }
            }

            if self.dataListAry.count == 0 {
                self.defultView.isHidden = false
            }
            else {
                self.defultView.isHidden = true
            }
        }
    }
    
    
    func delfavAction(collectID: String,callback: @escaping () -> Void) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "collectCode":collectID]
        API.request(url: .M_DeleteCollection, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                callback()
            }
            else {
                let popup = PopupBox(infoText: result.errMsg ?? "移除收藏失败")
                popup.show(vc: UIViewController.topMostController() ?? self)
            }
        }
    }
}


// MARK: UI
extension M_FavListVC {
    func setupUI() {
        safeView.backgroundColor = .xF2F2F2
        headView.backgroundColor = .white
        headTitle.text = "收藏"
        
//        drawRightButton(imageName: "xiaoxi_4")
//        .addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        let newsButton = drawRightButton(imageName: "xiaoxi_4")
        newsButton.addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        UnreadPointForNewsButton(button: newsButton, pointRadius: 3.5,
                                 pointOffset: .init(x: -9.5, y: 10),  color: .xE0551B)

        //画横线
        let line = headView.drawView { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        //添加列表
        let _ = getRefreshHeader()
        let _ = getRefreshFooter()
        safeView.addSubview(tableView)
        tableView.backgroundColor = UIColor.clear;
        tableView.register(M_FavCell.self, forCellReuseIdentifier: "M_FavCell")
        tableView.separatorStyle = .none
        tableView.dataSource = self
        tableView.delegate = self
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
    }

            func getRefreshHeader()->MJRefreshHeader {
        //        顶部的下拉初始化
                let header = MJRefreshNormalHeader()
                header.lastUpdatedTimeLabel.isHidden = true
                tableView.mj_header = header
                header.setTitle("下拉刷新...", for: .idle)
                header.setTitle("下拉刷新...", for: .pulling)
                header.setTitle("下拉更新中...", for: .refreshing)
                header.setTitle("完成...", for: .willRefresh)
                header.setTitle("下拉刷新...", for: .noMoreData)
                header.setRefreshingTarget(self, refreshingAction: #selector(onHeaderRequery))

        //        顶部的处理逻辑：
                return tableView.mj_header!
            }
            
            func getRefreshFooter()->MJRefreshFooter {
                if tableView.mj_footer == nil {
                    //        底部初始化：
                    let footer = MJRefreshAutoNormalFooter()
    //                footer.isOnlyRefreshPerDrag = true
                    tableView.mj_footer = footer
                    footer.setTitle("", for: .idle)
                    footer.setTitle("", for: .pulling)
                    footer.setTitle("下拉更新中...", for: .refreshing)
                    footer.setTitle("完成...", for: .willRefresh)
                    footer.setTitle("", for: .noMoreData)
                    footer.setRefreshingTarget(self, refreshingAction: #selector(onFooterLoadMore))
                }

        //        底部处理逻辑：
                if pageIndex * pageSize < totalSize {
                    tableView.mj_footer.endRefreshing()
                }
                else {
                    tableView.mj_footer.endRefreshingWithNoMoreData()
                }
                
        //        底部数据加载
                 return tableView.mj_footer!
            }
}

// MARK: event & action
extension M_FavListVC {
    func refreshAll() {
        self.getDataList(zoneCode: "105001", pageIndex: 1, pageSize: pageSize)
    }
    
    @objc func _xiaoxiButtonClick(button: Button) {
        let vc = M_NewsListVC()
        pushViewController(vc)
    }
    
    @objc func onHeaderRequery() {
        //        顶部数据重新加载
        getRefreshFooter().state = .idle
        tableView.mj_header.endRefreshing()
        
        refreshAll()
    }
    
    @objc func onFooterLoadMore() {
        //        底部数据重新加载更多底部处理逻辑：
        if pageIndex * pageSize < totalSize,dataListAry.count > 0 {
            self.getDataList(zoneCode: "105001", pageIndex: pageIndex+1, pageSize: pageSize)
            tableView.mj_footer.endRefreshing()
        }
        else {
            tableView.mj_footer.endRefreshingWithNoMoreData()
        }
    }
    
    ///MARK: UITableViewDelegate
    // 选中cell后执行此方法
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath.row)
        let dic = dataListAry[indexPath.row]
        let vc = M_ProductDetailVC(info: dic)
        self.pushViewController(vc)
    }
    
    ///MARK: UITableViewDataSource
    
    //组数
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataListAry.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellid = "M_FavCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: cellid) as? M_FavCell
        if cell==nil {
            cell = M_FavCell(style: .subtitle, reuseIdentifier: cellid)
        }
        
        cell?.celldata = dataListAry[indexPath.row]
        cell?.calldelBlock(block: { c in
            // 当点击了删除按钮
            let ip = tableView.indexPath(for: c)
            let dic = self.dataListAry[ip!.row]
             self.delfavAction(collectID: dic.getString("collectID") ?? "", callback: {
                 self.dataListAry.remove(at: indexPath.row)
                 tableView.reloadData()
            })
        })
        
        cell?.callmoreBlock(block:  { _ in
//            if tableView.isEditing {
//                if self.editRow != nil {
//                    let editcell = tableView.cellForRow(at: self.editRow!) as? M_FavCell
//                    editcell?.ermakeUINomal()
//                }
//                cell?.ermakeUINomal()
//                tableView.setEditing(false, animated: true)
//            }
//            else {
//                self.editRow = indexPath
//                cell?.ermakeUIEdit()
//                tableView.setEditing(true, animated: true)
//            }
        })
        return cell!
    }
    
    // 设置cell高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 140
    }
    
    //左划状态
//    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
//        let del = UITableViewRowAction(style: .default, title: "删除") { action, index in
//            // 当点击了删除按钮
//            let dic = self.dataListAry[indexPath.row]
//            self.delfavAction(collectID: dic.getString("collectID") ?? "", callback: {
//                self.dataListAry.remove(at: indexPath.row)
//                tableView.reloadData()
//            })
//        }
//        editRow = nil
//        del.backgroundColor = .red
//        tableView.setEditing(false, animated: false)
//        return [del]
//    }
//    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
//        if editRow == nil || indexPath.row == editRow?.row {
//            return true
//        }
//        return false
//    }
    
//    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
//
//    }
}
